package extension

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import androidx.activity.ComponentActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.*

val Number.dp
    get() = (TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        /*this.*/toFloat(),
        Resources.getSystem().displayMetrics
    ) + 0.5).toInt()

val Number.sp
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP,
        /*this.*/toFloat(),
        Resources.getSystem().displayMetrics)



// 四舍五入保留n位小数 "%.1f" todo 不能格式化整数？？
//fun Number.format(precision: Int = 1): String {
//  // 强制使用英文格式化，这种方式在俄文下有问题:java.lang.NumberFormatException: For input string: "39,1"
//  return String.format(Locale.US, "%.${precision}f", this)
//}

// 四舍五入保留n位小数
//fun Double.format(precision: Int = 1): String {
//  // 强制使用英文格式化，这种方式在俄文下有问题:java.lang.NumberFormatException: For input string: "39,1"
//  return String.format(Locale.US, "%.${precision}f", this)
//}
//
//fun Float.format(precision: Int = 1): String {
//  // 强制使用英文格式化，这种方式在俄文下有问题:java.lang.NumberFormatException: For input string: "39,1"
//  return String.format(Locale.US, "%.${precision}f", this)
//}

// 四舍五入保留n位小数，并强制显示小数，如10.00
fun Number.formatDecimal(precision: Int = 1): String {
    return withDefaultLocal(Locale.US) {
        var pattern = if (precision == 0) "0" else "0."
        for (index in 0 until precision) {
            pattern += "0"
        }
        DecimalFormat(pattern).apply {
            roundingMode = RoundingMode.HALF_UP
        }.format(this)
    }
}

fun <T> withDefaultLocal(newLocale: Locale, block: () -> T): T {
    val locale = Locale.getDefault()
    Locale.setDefault(newLocale)
    val result = block()
    Locale.setDefault(locale)
    return result
}

// 可以通过by
fun stringPref(num: Int): Lazy<String> {
    return StringPrefLazy(num)
}

inline fun <reified VM : ViewModel> ComponentActivity.viewModels2(
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM> {
    val factoryPromise = factoryProducer ?: {
        defaultViewModelProviderFactory
    }

    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
}

// At the top level of your kotlin file:
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")